from fastapi import APIRouter, Depends, HTTPException, status, UploadFile, File
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.core.deps import get_current_admin_user
from app.models.user import User
from app.models.project_file import ProjectFile, FileType
from app.services.oss_service import oss_service
from typing import Optional

router = APIRouter()

@router.post("/upload")
async def upload_file(
    file: UploadFile = File(...),
    project_id: Optional[int] = None,
    category: Optional[str] = None,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_admin_user)
):
    allowed_extensions = ['jpg', 'jpeg', 'png', 'pdf', 'mp4', 'mov']
    file_ext = file.filename.split('.')[-1].lower()
    
    if file_ext not in allowed_extensions:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="不支持的文件类型"
        )
    
    file_content = await file.read()
    file_url = oss_service.upload_file(file_content, file.filename, category or "general")
    
    if project_id:
        file_type = FileType.IMAGE
        if file_ext in ['mp4', 'mov']:
            file_type = FileType.VIDEO
        elif file_ext == 'pdf':
            file_type = FileType.DOCUMENT
        
        project_file = ProjectFile(
            project_id=project_id,
            file_type=file_type,
            file_url=file_url,
            file_name=file.filename,
            file_size=len(file_content),
            category=category
        )
        db.add(project_file)
        db.commit()
    
    return {
        "file_url": file_url,
        "file_name": file.filename,
        "file_size": len(file_content)
    }

@router.delete("/{file_id}")
def delete_file(
    file_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_admin_user)
):
    project_file = db.query(ProjectFile).filter(ProjectFile.id == file_id).first()
    if not project_file:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="文件不存在"
        )
    
    oss_service.delete_file(project_file.file_url)
    db.delete(project_file)
    db.commit()
    
    return {"message": "文件删除成功"}

